package com.yimi.policyservice.common.aop;

import com.yimi.policyservice.common.annotation.Auth;
import com.yimi.policyservice.common.constant.GloabConstant;
import com.yimi.policyservice.service.UserService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
public class ApiAop {

    @Autowired
    private UserService userService ;

    @Pointcut("execution(public * com.yimi.policyservice.controller.*.*(..))")
    public void controllerMethodCall() {
    }

    @Before(value = "controllerMethodCall()")
    public void authorize(JoinPoint joinPoint) {
        Method method = getControllerMethod(joinPoint);
        Auth auth = method.getAnnotation(Auth.class);
        if (auth != null) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            //TODO 校验token 和权限 request.getHeader()
            userService.checkLogin(request.getHeader(GloabConstant.tokenName),auth.code());
        }
    }

    private Method getControllerMethod(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        return signature.getMethod();
    }
}
